﻿using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Xml.Serialization;
using TfsComLib.TfsBranchLib2;

namespace TfsBranchLib2.Model
{
    /// <summary>
    ///     Для выделения из списка веток подсписка
    /// </summary>
    public class BranchFilter : INotifyPropertyChanged
    {
        private ISourceBranches branchProvider;

        private ObservableCollection<BranchData> collection;


        private bool isError;

        private ObservableCollection<BranchData> selectedBranches;

        public BranchFilter()
        {
            selectedBranches = new ObservableCollection<BranchData>();
            collection = new ObservableCollection<BranchData>();
        }

        [XmlIgnore]
        public ISourceBranches BranchProvider
        {
            get
            {
                //if (sourceBranches == null )
                return branchProvider;
            }
            set
            {
                branchProvider = value;
                NotifyPropertyChange("SourceBranches");
            }
        }

        public ObservableCollection<BranchData> BranchList
        {
            get
            {
                if (collection == null)
                {
                    UpdateCollection();
                }
                return collection;
            }
            set { }
        }

        public bool IsError
        {
            get { return isError; }
            set
            {
                isError = value;
                NotifyPropertyChange("IsError");
            }
        }

        public ObservableCollection<BranchData> SelectedBranches
        {
            get { return selectedBranches; }
            set
            {
                selectedBranches = value;
                NotifyPropertyChange("SelectedBranches");
            }
        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion

        public bool UpdateCollection()
        {
            if (BranchProvider != null)
            {
                var branchList = BranchProvider.GetBranchList();
                if ((!BranchProvider.IsErrorOrConnectionProblem) && (branchList != null))
                {
                    branchList.Sort((BranchData a, BranchData b) => { return string.Compare(a.Name, b.Name); });
                    collection = new ObservableCollection<BranchData>();
                    branchList.ForEach(
                        (BranchData branchData) => collection.Add(branchData));
                    SetSelectedBranches();
                    IsError = false;
                    return true;
                }
            }
            IsError = true;
            return false;
        }

        /// <summary>
        ///     Метод устанавливает IsSelected для полного списка BranchList по списку SelectedBranches
        ///     SelectedBranches > BranchList
        /// </summary>
        /// <returns></returns>
        public void SetSelectedBranches()
        {
            // Get selected branches List
            var selectedPaths = from branch in SelectedBranches
                select branch.ServerPath;
            foreach (var branch in BranchList)
            {
                if (selectedPaths.Contains(branch.ServerPath))
                {
                    branch.IsSelected = true;
                }
                else
                {
                    branch.IsSelected = false;
                }
            }
        }

        /// <summary>
        ///     Метод очищает SelectedBranches и добавляет туда из полного списка BranchList с атрибутом IsSelected = true
        ///     BranchList > SelectedBranches
        /// </summary>
        public void GetSelectedBranches()
        {
            var query = from branch in BranchList
                where branch.IsSelected
                select branch;
            SelectedBranches.Clear();
            foreach (var branchData in query)
            {
                SelectedBranches.Add(branchData);
            }
        }

        private void NotifyPropertyChange(string prop)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged.Invoke(this, new PropertyChangedEventArgs(prop));
            }
        }
    }
}